const DB = require('better-sqlite3-helper');
const { log } = require('./util')

const db = DB({
  path: './data/sqlite3.db', // this is the default
  readonly: false, // read only
  fileMustExist: false, // throw error if database not exists
  WAL: true, // automatically enable 'PRAGMA journal_mode = WAL'
  migrate: {  // disable completely by setting `migrate: false`
    force: false, // set to 'last' to automatically reapply the last migration-file
    table: 'migration', // name of the database table that is used to keep track
    migrationsPath: './migrations' // path of the migration-files
  }
})

const MAVEN = 'maven'
const BREAKPOINT = 'breakpoint'
const RUNNINT = 'running'
const BREAKPOINT_PK = 2

/**
 * 初始化断点表
 */
function init() {
  let row = db.queryFirstRow(`select * from ${BREAKPOINT} where pk=?`, BREAKPOINT_PK)
  if (!row) {
    db.insert(BREAKPOINT, { pk: BREAKPOINT_PK, url: '' })
  }
}

init()

const getRunning = () => {
  return db.query(`select url from ${RUNNINT}`).map(row => row.url)
}

const delRunning = (url) => {
  log.debug(`清理正在下载的文件：${url}`)
  db.delete(RUNNINT, { url })
}

const getBreakPoint = () => {
  return db.query(`select url from ${BREAKPOINT} where pk=?`, BREAKPOINT_PK).map(row => row.url)
}

const addBreakPoint = (url) => {
  log.debug(`保存进度：${url}`)
  db.insert(BREAKPOINT, {
    pk: BREAKPOINT_PK,
    url
  })
}

const delBreakPoint= (url) => {
  log.debug(`清除进度：${url}`)
  db.delete(BREAKPOINT, { url })
}

module.exports = {
  db,
  getHotMaven: () => {
    return db.query(`select distinct groupId from ${MAVEN}`)
  },
  saveMaven: (objs) => {
    db.insert(MAVEN, objs)
  },
  updateMaven: (obj) => {
    db.update(MAVEN, obj, { id: obj.id })
  },
  addRunning: (url) => {
    log.debug(`保存正在下载的文件：${url}`)
    db.insert(RUNNINT, { url })
  },
  clearRunning: () => {
    getRunning().forEach(delRunning)
  },
  clearBreakPoint: () => {
    getBreakPoint().forEach(delBreakPoint)
  },
  getRunning, delRunning, getBreakPoint, addBreakPoint, delBreakPoint
}